package com.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.model.auto.*;
import com.service.*;
import com.util.Page;
import com.util.R;
import com.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 学生管理
 *
 * @author astupidcoder
 * @since 2022-09-14
 */
@Slf4j
@RestController
@RequestMapping("/students")
public class StudentController{
    @Autowired
    private IStudentService studentService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IAchievementService achievementService;

    @Autowired
    private IContactsService contactsService;

    @Autowired
    private IGaoKaoConfigService gaoKaoConfigService;

    //新增+修改学生信息
    @PostMapping("/saveOrUpdateArchives")
    public R saveOrUpdateXuanKe(@RequestBody Student student) {
        if(student.getId()==null){
            List<Student> students=studentService.list(new LambdaQueryWrapper<Student>()
                    .eq(student.getCreatedUser()!=null,Student::getCreatedUser,student.getCreatedUser())
                    .orderByDesc(Student::getStuNum).last("limit 1")
            );
        }
        boolean result = studentService.saveOrUpdate(student);
        //保存学生联系人
        if(!ObjectUtils.isEmpty(student.getStuContacts())){
            student.getStuContacts().forEach(contact -> {
                contact.setStuId(student.getId());
                if(StringUtils.hasText(contact.getName())){
                    contactsService.saveOrUpdate(contact);
                }
            });

        }
        //保存学生成绩
        if(!ObjectUtils.isEmpty(student.getStuAchievements())){
            student.getStuAchievements().forEach(achievement -> {
                achievement.setStuId(student.getId());
            });
            achievementService.saveOrUpdateBatch(student.getStuAchievements());
        }

        if (result){
            return R.ok(student);
        }
        return R.error();

//        System.out.println("传过来的地址：" + student.getAddress() + "传过来的名字" + student.getName());

    }

    @GetMapping("/getStu")
    public R getStu(Integer Id){
        System.out.println("id是"+Id);
        Student student=studentService.getOne(new LambdaQueryWrapper<Student>()
        .eq(Student::getUserId,Id).eq(Student::getDeleted, false));
        if(!ObjectUtils.isEmpty(student)){
            List<Achievement> stuAchievements = achievementService.list(new LambdaQueryWrapper<Achievement>()
                    .eq(Achievement::getStuId, student.getId()));
            student.setStuAchievements(stuAchievements);
            List<Contacts> stuContacts = contactsService.list(new LambdaQueryWrapper<Contacts>()
                    .eq(Contacts::getStuId, student.getId()));
            student.setStuContacts(stuContacts);

            SysUser sysUser = sysUserService.getById(student.getUserId());
            if(Objects.nonNull(sysUser)){
                student.setOther(sysUser.getYear());
            }
        }
        return R.ok(student);
    }


    @GetMapping("/getStudent")
    public R getStudent(String id) {
        List<Student> list = studentService.list(new LambdaQueryWrapper<Student>()
                .eq(!StringUtil.isEmpty(id), Student::getCreatedUser, id)
                .eq(Student::getDeleted, false)
                .orderByDesc(Student::getOther)
                .orderByAsc(Student::getStuNum)
        );

        List<SysUser> users=sysUserService.list();
        users.forEach(i->{
            list.forEach(l->{
                if (l.getUserId()!=null&&i.getUserId().equals((long)l.getUserId())){
                    l.setCardCode(i.getCardCode());
                    l.setOther(i.getYear());
                }
            });
        });

        list.forEach(student -> {
            if(!ObjectUtils.isEmpty(student)){
                List<Achievement> stuAchievements = achievementService.list(new LambdaQueryWrapper<Achievement>()
                        .eq(Achievement::getStuId, student.getId()));
                student.setStuAchievements(stuAchievements);
                List<Contacts> stuContacts = contactsService.list(new LambdaQueryWrapper<Contacts>()
                        .eq(Contacts::getStuId, student.getId()));
                student.setStuContacts(stuContacts);
            }
        });

        return R.ok(list);
    }

    @GetMapping("/getStudentById")
    public R getStudentById(Integer id) {
        List<Student> list = studentService.list(new LambdaQueryWrapper<Student>()
                .eq(!ObjectUtils.isEmpty(id), Student::getId, id)
                .eq(Student::getDeleted, false)
                .orderByDesc(Student::getOther)
                .orderByAsc(Student::getStuNum)
        );
        if(ObjectUtils.isEmpty(list)){
            return R.error("未查询到学生");
        }
        Student student = list.get(0);
        if(!ObjectUtils.isEmpty(student)){
            List<Achievement> stuAchievements = achievementService.list(new LambdaQueryWrapper<Achievement>()
                    .eq(Achievement::getStuId, student.getId()));
            student.setStuAchievements(stuAchievements);
            List<Contacts> stuContacts = contactsService.list(new LambdaQueryWrapper<Contacts>()
                    .eq(Contacts::getStuId, student.getId()));
            student.setStuContacts(stuContacts);

            SysUser sysUser = sysUserService.getById(student.getUserId());
            if(Objects.nonNull(sysUser)){
                student.setOther(sysUser.getYear());
            }
        }

        return R.ok(student);
    }

    @GetMapping("/getOneStudent")
    public R getOneStudent(String id, String name, String school, String year) {
        List<Student> list = studentService.list(new LambdaQueryWrapper<Student>()
                .eq(!StringUtil.isEmpty(id), Student::getCreatedUser, id)
                .like(!StringUtil.isEmpty(name), Student::getName, name)
                .like(!StringUtil.isEmpty(school), Student::getSchool, school)
                .eq(!StringUtil.isEmpty(year), Student::getOther, year)
                .eq(Student::getDeleted, false)
        );
        List<SysUser> users=sysUserService.list();
        users.forEach(i->{
            list.forEach(l->{
                if (l.getUserId()!=null&&i.getUserId().equals((long)l.getUserId())){
                    l.setCardCode(i.getCardCode());
                    l.setOther(i.getYear());
                }
            });
        });
        list.forEach(student -> {
            if(!ObjectUtils.isEmpty(student)){
                List<Achievement> stuAchievements = achievementService.list(new LambdaQueryWrapper<Achievement>()
                        .eq(Achievement::getStuId, student.getId()));
                student.setStuAchievements(stuAchievements);
                List<Contacts> stuContacts = contactsService.list(new LambdaQueryWrapper<Contacts>()
                        .eq(Contacts::getStuId, student.getId()));
                student.setStuContacts(stuContacts);
            }
        });
        return R.ok(list);
    }

    /**
     * 分页查询学生
     * @param page
     * @param id
     * @param name
     * @param school
     * @param year
     * @return
     */
    @GetMapping("/getOneStudentPage")
    public R getOneStudent(Page page, String id, String name, String school, String year) {
        PageInfo<Object> pageInfo = PageHelper.startPage(page.getPageNum(), page.getPageSize())
                .doSelectPageInfo(() -> {
                    List<Student> list = studentService.list(new LambdaQueryWrapper<Student>()
                            .eq(!StringUtil.isEmpty(id), Student::getCreatedUser, id)
                            .like(!StringUtil.isEmpty(name), Student::getName, name)
                            .like(!StringUtil.isEmpty(school), Student::getSchool, school)
                            .eq(!StringUtil.isEmpty(year), Student::getOther, year)
                            .eq(Student::getDeleted, false)
                            .orderByDesc(Student::getOther)
                            .orderByAsc(Student::getStuNum)
                    );
                    List<SysUser> users=sysUserService.list();
                    users.forEach(i->{
                        list.forEach(l->{
                            if (l.getUserId()!=null&&i.getUserId().equals((long)l.getUserId())){
                                l.setCardCode(i.getCardCode());
                                l.setOther(i.getYear());
                            }
                        });
                    });
                    list.forEach(student -> {
                        if(!ObjectUtils.isEmpty(student)){
                            List<Achievement> stuAchievements = achievementService.list(new LambdaQueryWrapper<Achievement>()
                                    .eq(Achievement::getStuId, student.getId()));
                            student.setStuAchievements(stuAchievements);
                            List<Contacts> stuContacts = contactsService.list(new LambdaQueryWrapper<Contacts>()
                                    .eq(Contacts::getStuId, student.getId()));
                            student.setStuContacts(stuContacts);
                        }
                    });
                });

        return R.ok(pageInfo);
    }

    /**
     * 分页查询已删除学生
     * @param page
     * @param id
     * @param name
     * @param school
     * @param year
     * @return
     */
    @GetMapping("/getDeleteStudentPage")
    public R getDeleteStudentPage(Page page, String id, String name, String school, String year) {
        PageInfo<Object> pageInfo = PageHelper.startPage(page.getPageNum(), page.getPageSize())
                .doSelectPageInfo(() -> {
                    List<Student> list = studentService.list(new LambdaQueryWrapper<Student>()
                            .eq(!StringUtil.isEmpty(id), Student::getCreatedUser, id)
                            .like(!StringUtil.isEmpty(name), Student::getName, name)
                            .like(!StringUtil.isEmpty(school), Student::getSchool, school)
                            .eq(!StringUtil.isEmpty(year), Student::getOther, year)
                            .eq(Student::getDeleted, true)
                            .orderByDesc(Student::getOther)
                            .orderByAsc(Student::getStuNum)
                    );
                    List<SysUser> users=sysUserService.list();
                    users.forEach(i->{
                        list.forEach(l->{
                            if (l.getUserId()!=null&&i.getUserId().equals((long)l.getUserId())){
                                l.setCardCode(i.getCardCode());
                                l.setOther(i.getYear());
                            }
                        });
                    });
                    list.forEach(student -> {
                        if(!ObjectUtils.isEmpty(student)){
                            List<Achievement> stuAchievements = achievementService.list(new LambdaQueryWrapper<Achievement>()
                                    .eq(Achievement::getStuId, student.getId()));
                            student.setStuAchievements(stuAchievements);
                            List<Contacts> stuContacts = contactsService.list(new LambdaQueryWrapper<Contacts>()
                                    .eq(Contacts::getStuId, student.getId()));
                            student.setStuContacts(stuContacts);
                        }
                    });
                });

        return R.ok(pageInfo);
    }

    //删除学生
    @GetMapping("/deleteStu")
    public R deleteStu(Integer id){
        Student ok=studentService.updateStu(id);
        return R.ok(ok);

    }

    /**
     * 恢复学生
     * @param id
     * @return
     */
    @GetMapping("/restoreStu")
    public R restoreStu(Integer id){
        Student ok= studentService.restoreStu(id);
        return R.ok(ok);

    }
    /**
     * 彻底删除
     * @param id
     * @return
     */
    @GetMapping("/relDeleteStu")
    public R relDeleteStu(Integer id){
        studentService.relDeleteStu(id);
        return R.ok();
    }

    //调整排序
    @PostMapping("UpdateSort")
    public R UpdateSort(@RequestBody Student[] students) {
        boolean update = studentService.saveOrUpdateBatch(Arrays.asList(students));
        if (update) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 获取学生更新选科、高考分数配置
     * @param stuId
     * @return
     */
    @GetMapping("/getUpdateMsgStatus")
    public R getUpdateMsgStatus(Integer stuId){
        Student student = studentService.getById(stuId);
        Boolean showMajor = false;
        Boolean showScore = false;
        Boolean disableFunction = false;
        try{
            List<GaoKaoConfig> list = gaoKaoConfigService.list();
            if(Objects.isNull(list)){
                return R.ok().put("showMajor", showMajor).put("disabledScore", showScore).put("disableFunction", disableFunction);
            }
            GaoKaoConfig gaoKaoConfig = list.get(0);

            SysUser user = sysUserService.getById(student.getUserId());
            if(Objects.isNull(user)){
                return R.ok().put("showMajor", showMajor).put("disabledScore", showScore).put("disableFunction", disableFunction);
            }

            if(StringUtils.hasText(gaoKaoConfig.getUserId())){
                List<String> configUserId = Arrays.asList(gaoKaoConfig.getUserId().split(","));
                if(!configUserId.contains(user.getUserId()+"")){
                    return R.ok().put("showMajor", showMajor).put("showScore", showScore).put("disableFunction", disableFunction);
                }
            }

            if(!student.getDisabledMajor()){
                //如果配置年份等于学生高考年份   并且当前时间大于等于配置选科修改时间
                if(user.getYear().equals(gaoKaoConfig.getMajorYear()) &&
                        LocalDateTime.now().compareTo(gaoKaoConfig.getMajorDate()) >= 0){
                    showMajor = true;
                }
            }
            if(!student.getDisabledScore()){
                if(LocalDateTime.now().compareTo(gaoKaoConfig.getScoreDate()) >= 0){
                    showScore = true;
                }
            }
            if(Objects.nonNull(gaoKaoConfig.getStartDate()) && Objects.nonNull(gaoKaoConfig.getEndDate())){
                if(gaoKaoConfig.getStartDate().isBefore(LocalDateTime.now()) && gaoKaoConfig.getEndDate().isAfter(LocalDateTime.now())){
                    if(user.getUserLevel() == 2 || user.getYear() != String.valueOf(LocalDateTime.now().getYear())){
                        disableFunction = true;
                    }
                }
            }

        }catch (Exception e){
            log.error("获取学生更新选科、高考分数配置异常，异常信息=", e);
        }
        return R.ok().put("showMajor", showMajor).put("showScore", showScore).put("disableFunction", disableFunction);
    }

}
